﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EM.Repository.utility;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Telerik.WebControls;

namespace EM.reports.income
{
    public partial class _default : System.Web.UI.Page
    {
        protected Conversion oC = new Conversion();
        protected DbHelper dsrv = new DbHelper();

        FillCombo fc = new FillCombo();


        private bool hasFULLAccess = false;
        private bool hasBMAccess = false;
        private bool hasLIMITEDAccess = false;

        protected void Page_Load(object sender, EventArgs e)
        {

            Authentication ua = new Authentication();
            ua.CheckRolePageAuthentication(20, Authentication.RedirectionURLTypes.LoginPage);

            hasFULLAccess = ua.HasPageFunctionAuthentication(20, "FULL");
            hasBMAccess = ua.HasPageFunctionAuthentication(20, "BM");
            hasLIMITEDAccess = ua.HasPageFunctionAuthentication(20, "LIMITED");

            if (!Page.IsPostBack)
            {
                fc.IncomeType(ddlINCOMETYPE, 0, true, Convert.ToInt32(Session["WORKGROUPID"]));

                if (hasFULLAccess)
                {
                    fc.User(ddlUSER, "0", true, Convert.ToInt32(Session["WORKGROUPID"]));
                    ddlUSER.Enabled = true;
                }
                else
                {
                    if (hasBMAccess)
                    {
                        fc.User(ddlUSER, "0", true, Convert.ToInt32(Session["BRANCHID"]));
                        ddlUSER.Enabled = true;
                    }
                    else
                    {
                        ddlUSER.Enabled = false;
                    }
                }
            }
        }

        private DataTable LoadData()
        {
            SqlCommand cmd = new SqlCommand();
            StringBuilder builder = new StringBuilder();
            builder.Append(@"SELECT INCOMEID, I.INCOMETYPEID, INCOMETYPENAME, CONVERT(NVARCHAR,INCOMEDATE,104) AS INCOMEDATE,
                            AMOUNT, U.USERDESC AS INCOMEUSER  FROM TBLINCOME I, TBLINCOMETYPE IT, TBLUSER U
                            WHERE I.INCOMETYPEID = IT.INCOMETYPEID AND I.INCOMEUSERID = U.USERID AND I.WORKGROUPID = " + Session["WORKGROUPID"]);

            if (ddlINCOMETYPE.SelectedValue != "" && ddlINCOMETYPE.SelectedValue != "0")
            {
                builder.Append(" AND I.INCOMETYPEID = @INCOMETYPEID");
                cmd.Parameters.AddWithValue("@INCOMETYPEID", ddlINCOMETYPE.SelectedValue);
            }

            if (!hasFULLAccess)
            {
                if (hasBMAccess)
                {
                    builder.Append(" AND I.BRANCHID = @BRANCHID");
                    cmd.Parameters.AddWithValue("@BRANCHID", Session["BRANCHID"]);

                    if (ddlUSER.SelectedValue != "" && ddlUSER.SelectedValue != "0")
                    {
                        builder.Append(" AND I.INCOMEUSERID = @INCOMEUSERID");
                        cmd.Parameters.AddWithValue("@INCOMEUSERID", ddlUSER.SelectedValue);
                    }
                }
                else
                {
                    builder.Append(" AND I.INCOMEUSERID = @INCOMEUSERID");
                    cmd.Parameters.AddWithValue("@INCOMEUSERID", Session["USERID"]);
                }
            }
            else
            {
                if (ddlUSER.SelectedValue != "" && ddlUSER.SelectedValue != "0")
                {
                    builder.Append(" AND I.INCOMEUSERID = @INCOMEUSERID");
                    cmd.Parameters.AddWithValue("@INCOMEUSERID", ddlUSER.SelectedValue);
                }
            }

            if (rdpSTARTDATE.SelectedDate != rdpSTARTDATE.MinDate)
            {
                builder.Append(" AND I.INCOMEDATE >= @INCOMEDATESTART");
                cmd.Parameters.AddWithValue("@INCOMEDATESTART", rdpSTARTDATE.SelectedDate);
            }

            if (rdpENDDATE.SelectedDate != rdpENDDATE.SelectedDate)
            {
                builder.Append(" AND I.INCOMEDATE <= @INCOMEEND");
                cmd.Parameters.AddWithValue("@INCOMEEND", rdpENDDATE.SelectedDate);
            }

            cmd.CommandText = builder.ToString();


            DataTable dt = this.dsrv.GetDataTable(cmd, "INCOME");
            return dt;
        }

        private void BindGrid()
        {
            DataTable dt = new DataTable();
            dt = LoadData();
            rgMaster.DataSource = dt;

            rgMaster.MasterTableView.NoMasterRecordsText = "Kayıt bulunamadı.";
            rgMaster.StatusBarSettings.ReadyText = dt.Rows.Count + " adet kayıt bulundu.";

            rgMaster.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }


        double totalAmount = 0;
        double totalAmountTotal = 0;

        protected void rgMaster_ItemDataBound(object sender, GridItemEventArgs e)
        {
            Conversion oC = new Conversion();
            DataRowView drw = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.Item)
            {
                DataRowView row = e.Item.DataItem as DataRowView;

                double amount = 0;
                if (row["AMOUNT"].ToString() != "")
                    amount = Convert.ToDouble(row["AMOUNT"]);


                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Text = oC.CNumS2C(amount);

                totalAmount += amount;
            }
            else if (e.Item.ItemType == GridItemType.Footer)
            {

                DataTable dt = rgMaster.DataSource as DataTable;

                totalAmountTotal = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    totalAmountTotal += Convert.ToDouble(dt.Rows[i]["AMOUNT"]);
                }

                e.Item.Cells[rgMaster.Columns.FindByUniqueName("INCOMEDATE").OrderIndex].Text = "Sayfa Toplamı :<br />Genel Toplam :";
                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Style.Add("text-align", "right");
                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Text = oC.CNumS2C(totalAmount) + "<br /> " + oC.CNumS2C(totalAmountTotal);

                totalAmount = 0;
                totalAmountTotal = 0;
            }
            else if (e.Item.ItemType == Telerik.WebControls.GridItemType.Pager)
            {
                Label lblRecordCount = new Label();
                e.Item.Controls[0].Controls.AddAt(0, lblRecordCount);
                lblRecordCount.Text = rgMaster.StatusBarSettings.ReadyText + " | sayfaya git : ";

                rgMaster.ShowStatusBar = rgMaster.PageCount <= 1 ? true : false;
            }
        }

        protected void rgMaster_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
        {
            if (IsPostBack)
            {
                DataTable dt = new DataTable();
                dt = LoadData();
                rgMaster.DataSource = dt;

                rgMaster.MasterTableView.NoMasterRecordsText = "Kayıt bulunamadı.";
                rgMaster.StatusBarSettings.ReadyText = dt.Rows.Count + " adet kayıt bulundu.";
            }
        }

        protected void rgMaster_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Page" || e.CommandName == "Sort")
            {
                BindGrid();
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                rgMaster.ExportSettings.FileName = "Income";
                rgMaster.ExportSettings.ExportOnlyData = true;
                rgMaster.ExportSettings.IgnorePaging = true;
                rgMaster.ExportSettings.OpenInNewWindow = true;
                rgMaster.MasterTableView.ExportToExcel();
            }
            catch
            {
                ;
            }
        }
    }
}